package com.ror.java.se.array;

/**
 * 五子棋案例（稀疏数组）
 * 棋盘：11*11
 * 功能：存盘、续盘
 */

public class Demo05ChessSheet {
    static int sheetRow = 11;
    static int sheetCol = 11;

    public static void main(String[] args) {
        int[][] src = new int[sheetRow][sheetCol];
        src[0][1] = 1;
        src[8][4] = 2;
        src[7][3] = 5;
        src[9][2] = 6;

        // 打印原始矩阵
        System.out.println("原始矩阵:");
        printMatrix(src);

        // 转换为稀疏矩阵
        // 1 获取有效值个数
        int valCnt = 0;
        for (int row = 0; row < sheetRow; row++) {
            for (int col = 0; col < sheetCol; col++) {
                if (src[row][col] != 0) {
                    valCnt++;
                }
            }
        }
        System.out.println("有效值个数：" + valCnt);

        // 2 创建稀疏矩阵
        int[][] res = new int[valCnt + 1][3];
        int valIdx = 0;
        res[valIdx] = new int[]{sheetRow, sheetCol, valCnt};
        for (int row = 0; row < sheetRow; row++) {
            for (int col = 0; col < sheetCol; col++) {
                if (src[row][col] != 0) {
                    valIdx++;
                    res[valIdx] = new int[]{row, col, src[row][col]};
                }
            }
        }

        // 3 打印稀疏矩阵
        System.out.println("稀疏矩阵：");
        for (int[] row : res) {
            System.out.println(row[0] + "\t" + row[1] + "\t" + row[2]);
        }

        // 还原为原始矩阵
        int[][] loaded = new int[res[0][0]][res[0][1]];

        for (int i = 1; i < res.length; i++){
            loaded[res[i][0]][res[i][1]] = res[i][2];
        }

        System.out.println("还原的矩阵：");
        printMatrix(loaded);

    }

    private static void printMatrix(int[][] mtx) {
        for (int[] row : mtx) {
            for (int dot : row) {
                System.out.print(dot + " ");
            }
            System.out.println();
        }
    }
}
